package com.song.secure;

import java.util.Collection;
import java.util.Iterator;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Repository;

import com.song.secure.service.RoleService;
public class CustomAccessDecisionManagerImpl implements
		CustomAccessDecisionManager {
	
	@Resource
	private RoleService  roleService;
	
	public void decide(Authentication authentication, Object object,
			Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
		
		if (null == configAttributes) {
			return;
		}
		//���ʸ�uri����Ҫ�Ľ�ɫ�б�
		Iterator<ConfigAttribute> cons = configAttributes.iterator();

		while (cons.hasNext()) {
			ConfigAttribute ca = cons.next();
			String needRole = ((SecurityConfig) ca).getAttribute();//���ʸ���Դ����Ҫ��Ȩ��
			for (GrantedAuthority gra : authentication.getAuthorities()) {//gra:���û�ӵ�е�Ȩ��
				if (needRole.trim().equals(gra.getAuthority().trim())) {
					//����
					return;
				}
			}
		}
		//���û�û��Ȩ�޷��ʸ���Դ
		throw new AccessDeniedException("Access Denied");
	

	}

	public boolean supports(ConfigAttribute attribute) {
		return true;
	}

	public boolean supports(Class<?> clazz) {
		return true;
	}

	public RoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	
}
